from flask import Blueprint, render_template, jsonify, request

from app import db
from app.models import User

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return render_template('index.html', title='首页')

@main.route('/about')
def about():
    return render_template('index.html', title='关于我们')


# 新增的 API 接口
# 获取所有用户 (GET)
@main.route('/api/users', methods=['GET'])
def get_users():
    try:
        users = User.query.all()
        return jsonify({
            'success': True,
            'data': [{
                'username': user.username,
                'password': user.password
            } for user in users]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

# 获取单个用户 (GET)
@main.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    try:
        user = User.query.get_or_404(user_id)
        return jsonify({
            'success': True,
            'data': {
                'username': user.username,
                'password': user.password
            }
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 404


# 创建新用户 (POST)
@main.route('/api/users', methods=['POST'])
def create_user():
    try:
        data = request.get_json()

        # 验证必要字段
        if not data or not data.get('username') or not data.get('password'):
            return jsonify({
                'success': False,
                'message': '用户名和密码是必填字段'
            }), 400

        # 检查用户是否已存在
        existing_user = User.query.filter(
            (User.username == data['username'])
        ).first()

        if existing_user:
            return jsonify({
                'success': False,
                'message': '用户名'
            }), 400

        # 创建新用户
        user = User(
            username=data['username'],
            password=data['password']
        )
        db.session.add(user)
        db.session.commit()

        return jsonify({
            'success': True,
            'message': '用户创建成功',
            'data': {
                'username': user.username,
                'password': user.password
            }
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500


# 更新用户 (PUT)
@main.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json()

        # 更新字段
        if 'username' in data:
            user.username = data['username']
        if 'password' in data:
            user.password = data['password']

        db.session.commit()

        return jsonify({
            'success': True,
            'message': '用户更新成功',
            'data': {
                'username': user.username,
                'password': user.password
            }
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500


# 删除用户 (DELETE)
@main.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    try:
        user = User.query.get_or_404(user_id)
        db.session.delete(user)
        db.session.commit()

        return jsonify({
            'success': True,
            'message': '用户删除成功'
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500